package club.justwill.single.persistence.dao;

import club.justwill.single.persistence.jpo.Invitation;
import club.justwill.single.persistence.support.BaseDao;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by luoyu on 15-12-27.
 */
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class InvitationDao extends BaseDao<Invitation> {

    public Invitation getByInviterIdAndIntiteeId(long inviterId, long inviteeId){
        Query query = em.createNamedQuery("Invitation.getByInviterIdAndInviteeId")
                .setParameter("inviterId",inviteeId).setParameter("inviteeId",inviteeId);
        try {
            return (Invitation) query.getSingleResult();
        } catch (NonUniqueResultException e){
            return (Invitation) query.getResultList().get(0);
        } catch (NoResultException e) {
            return null;
        }
    }

    public List searchInvitations(long inviterId, int index, int size) {
        Query query = em.createNamedQuery("Invitation.searchByInviterId")
                .setParameter("inviterId",inviterId).setFirstResult(index).setMaxResults(size);

        return query.getResultList();
    }

    public Long getInviteeIdCount(long inviterId) {
        Query query = em.createNamedQuery("Invitation.getInviteeIdCount")
                .setParameter("inviterId",inviterId);
        try {
            return (Long) query.getSingleResult();
        } catch (NonUniqueResultException e){
            return (Long) query.getResultList().get(0);
        } catch (NoResultException e) {
            return null;
        }
    }
}
